package com.example.demo05.controller;


import com.example.demo05.pojo.User;
import com.example.demo05.pojo.UserResp;
import com.example.demo05.service.UserService;
import com.example.demo05.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author anxuan
 * @since 2021-06-17
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    // 测试
    @GetMapping("/test")
    @PreAuthorize("hasAuthority('管理员')")
    public void test(HttpServletResponse response) throws IOException {

         JsonResult result = ResultTool.success("管理员");
         TurnJson.JsonWrite(response,result);
//        log.info("进来了Cookies:{}",request.getCookies());
//        return userService.list();


    }

    //注册
    @PostMapping("/register")
    @PreAuthorize("hasAuthority('管理员')")
    public void register(@RequestBody User user, HttpServletResponse response) throws IOException {


        if(userService.getByLoginId(user.getLoginid()) !=null){
            JsonResult result=ResultTool.fail(ResultCode.EXIT_FAIL);
            TurnJson.JsonWrite(response,result);
        }
        else {
            String password = user.getPassword();
            log.info("密码，{}", password);
            log.info("User，{}", user);
            //user.setCreatetime(new Date());
            //user.setUpdatetime(new Date());
            //user.setAcountnonlocked(true);
            user.setPassword(passwordEncoder.encode(password));
            log.info("User，{}", user);
            boolean flag = false;

            try {
                log.info("flag,{}", flag);
                flag = userService.save(user);

            } catch (Exception e) {
                JsonResult result = ResultTool.fail();
                TurnJson.JsonWrite(response, result);
            }
            if (flag) {
                JsonResult result = ResultTool.success("注册成功");
                TurnJson.JsonWrite(response, result);
            } else {
                JsonResult result = ResultTool.fail();
                TurnJson.JsonWrite(response, result);
            }

        }
    }

    //防水墙检查
    @PostMapping("/check")
    public int check(@RequestParam String ticket,@RequestParam String randstr){
        log.info("进入check！");
        log.info("ticket:{}",ticket);
        log.info("randstr:{}",randstr);
        return TCaptchaVerify.verifyTicket(ticket,randstr);
    }


    //学生用户显示
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('管理员')")
    public List<UserResp> commonList(){
        List<User> users = userService.getByIdentity("学生");
        log.info("users:{}",users);
        return CopyUtil.copyList(users,UserResp.class);
    }

    //学生用户锁定
    @PostMapping("/locked")
    @PreAuthorize("hasAuthority('管理员')")
    public void locked(@RequestParam String loginid){

        log.info("进入locked(),{}",loginid);
        User user = userService.getByLoginId(loginid);
        user.setAcountnonlocked(false);
        userService.updateById(user);
        log.info("锁定成功");

    }

    //学生用户解锁
    @PostMapping("/unlocked")
    @PreAuthorize("hasAuthority('管理员')")
    public void unlocked(@RequestParam String loginid){

        log.info("进入locked(),{}",loginid);
        User user = userService.getByLoginId(loginid);
        user.setAcountnonlocked(true);
        userService.updateById(user);
        log.info("解锁成功");

    }


    //学号模糊查询学生用户
    @GetMapping("/selectLikeId")
    @PreAuthorize("hasAuthority('管理员')")
    public List<UserResp> selectById(@RequestParam String loginid){
//        User user = userService.getByLoginId(loginid);
        if(!ObjectUtils.isEmpty(loginid)) {
            List<User> users = userService.getLikeLoginId(loginid);
            log.info("users:{}",users);
            return CopyUtil.copyList(users, UserResp.class);
        }else{
            List<User> users = userService.getByIdentity("学生");
//            log.info("users:{}",users);
            return CopyUtil.copyList(users,UserResp.class);
        }
    }

    //显示所有管理员用户
    @GetMapping("/adminlist")
    @PreAuthorize("hasAuthority('管理员')")
    public List<UserResp> adminList(){
        List<User> users = userService.getByIdentity("管理员");
        log.info("users:{}",users);
        return CopyUtil.copyList(users,UserResp.class);
    }

    //通过账号模糊管理员用户
    @GetMapping("/selectAdminLikeId")
    @PreAuthorize("hasAuthority('管理员')")
  public List<UserResp> selectAdminLikeId(@RequestParam String loginid){
        //  User user = userService.getByLoginId(loginid);
        if(!ObjectUtils.isEmpty(loginid)) {
            List<User> users = userService.getAdminLikeLoginId(loginid);
            log.info("users:{}",users);
            return CopyUtil.copyList(users, UserResp.class);
        }else{
            List<User> users = userService.getByIdentity("管理员");
//            log.info("users:{}",users);
            return CopyUtil.copyList(users,UserResp.class);
        }
    }

    //添加管理员用户
    @PostMapping("/addAdmin")
    @PreAuthorize("hasAuthority('管理员')")
    public void addAdmin(@RequestBody User user,HttpServletResponse response) throws IOException {


        log.info("adduser:{}",user);
        //userService.save(user);
        if(userService.getByLoginId(user.getLoginid()) !=null){
            JsonResult result=ResultTool.fail(ResultCode.EXIT_FAIL);
            TurnJson.JsonWrite(response,result);
        }
        else {
            user.setIdentity("管理员");
            String password = user.getPassword();
            log.info("密码，{}", password);
            log.info("User，{}", user);
            user.setPassword(passwordEncoder.encode(password));
            log.info("User，{}", user);
            boolean flag = false;

            try {
                log.info("flag,{}", flag);
                flag = userService.save(user);

            } catch (Exception e) {
                JsonResult result = ResultTool.fail();
                TurnJson.JsonWrite(response, result);
            }
            if (flag) {
                JsonResult result = ResultTool.success("添加成功");
                TurnJson.JsonWrite(response, result);
            } else {
                JsonResult result = ResultTool.fail();
                TurnJson.JsonWrite(response, result);
            }

        }

    }

    //删除管理员用户
    @DeleteMapping("/delete")
    @PreAuthorize("hasAuthority('管理员')")
    public void delete(@RequestParam(value = "loginid") String loginid){
        log.info("进入删除");
        userService.delete(loginid);
    }


    //获取学生本人用户 用于疫情打卡
    @GetMapping("/getUser")
    @PreAuthorize("hasAuthority('学生')")
    public UserResp getUser(@RequestParam String loginid){
         User user = userService.getByLoginId(loginid);
         return CopyUtil.copy(user,UserResp.class);
    }


    @PostMapping("/editAdmin")
    @PreAuthorize("hasAuthority('管理员')")
    public void editAdmin(@RequestBody User user,HttpServletResponse response) throws IOException {

        User usertemp =userService.getByLoginId(user.getLoginid());
        user.setId(usertemp.getId());
        user.setIdentity(usertemp.getIdentity());
        user.setPassword(usertemp.getPassword());
        user.setFlag(usertemp.getFlag());
        user.setAcountnonlocked(usertemp.getAcountnonlocked());

        boolean flag = false;

        try {
            //log.info("flag,{}", flag);
            flag = userService.updateById(user);

        } catch (Exception e) {
            JsonResult result = ResultTool.fail();
            TurnJson.JsonWrite(response, result);
        }
        if (flag) {
            JsonResult result = ResultTool.success("修改成功");
            TurnJson.JsonWrite(response, result);
        } else {
            JsonResult result = ResultTool.fail();
            TurnJson.JsonWrite(response, result);
        }

    }


    //重置密码
    @PostMapping("/resetPassword")
    @PreAuthorize("hasAuthority('管理员')")
    public void resetPassword(@RequestBody User user,HttpServletResponse response) throws IOException {

        log.info("前端传输的密码{}",user.getPassword());
        User usertemp =userService.getByLoginId(user.getLoginid());
        user.setId(usertemp.getId());
        user.setIdentity(usertemp.getIdentity());
        user.setPassword(passwordEncoder.encode(user.getPassword()));


        boolean flag = false;

        try {
            //log.info("flag,{}", flag);
            flag = userService.updateById(user);

        } catch (Exception e) {
            JsonResult result = ResultTool.fail();
            TurnJson.JsonWrite(response, result);
        }
        if (flag) {
            JsonResult result = ResultTool.success("修改成功");
            TurnJson.JsonWrite(response, result);
        } else {
            JsonResult result = ResultTool.fail();
            TurnJson.JsonWrite(response, result);
        }
    }



}

